import 'package:enjoy_plus/models/house_list_model.dart';
import 'package:enjoy_plus/models/repair_model.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/logger.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/upload_image.dart';
import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:provider/provider.dart';
import 'package:enjoy_plus/providers/repair_provider.dart';

class AddRepair extends StatefulWidget {
  const AddRepair({super.key});

  @override
  State<AddRepair> createState() => _AddRepairState();
}

class _AddRepairState extends State<AddRepair> {
  TextEditingController phoneController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();

  // 报修项目列表
  List<RepairItem> repairItems = [];
  List<DatumItem> rooms = [];

  //请求获取报修项目
  Future fetchRepairItems() async {
    final response = await http.get<List<RepairItem>>('/repairItem',
        fromJson: (json) =>
            (json as List).map((item) => RepairItem.fromJson(item)).toList());
    logger.d(response.data.toString());
    setState(() {
      repairItems = response.data;
    });
  }

  // 获取房屋列表
  getRoomList() async {
    final res = await http.get<List<DatumItem>>('/room',
        fromJson: (json) =>
            List<DatumItem>.from(json.map((x) => DatumItem.fromJson(x))));
    logger.d(res.data.toString());
    if (mounted) {
      setState(() {
        rooms = res.data;
        if (rooms.isNotEmpty) {
          context.read<RepairProvider>().setSelectedHouse(rooms[0].name);
        }
      });
    }
  }

  // 添加图片
  addImage() async {
    String? imageUrl = await UploadImage.selectAvatar(context);
    // logger.d('imageUrl:---$imageUrl---');
    if (imageUrl != '') {
      setState(() {
        context
            .read<RepairProvider>()
            .setImageUrlList(ImageAttachment(id: '', url: imageUrl!));
      });
    }
  }

  // 提交报修
  submitRepair() async {
    final res = await http.post('/repair',
        data: {
          "houseId": rooms
              .firstWhere((room) =>
                  room.name == context.read<RepairProvider>().selectedHouse)
              .id,
          "repairItemId": repairItems
              .firstWhere((item) =>
                  item.name == context.read<RepairProvider>().selectedRepair)
              .id,
          "mobile": context.read<RepairProvider>().phoneNumber,
          "appointment": context.read<RepairProvider>().selectedDate,
          "description": context.read<RepairProvider>().problemDescription,
          "attachment": context
              .read<RepairProvider>()
              .imageUrlList
              .map((item) => {"id": item.id, "url": item.url})
              .toList()
        },
        fromJson: (json) => json);
    logger.d(res.data.toString());
    ToastUtil.showSuccess('提交成功');
  }

  // 加载页面时
  @override
  void initState() {
    super.initState();
    fetchRepairItems();
    getRoomList();

    // 初始化时设置controller的值
    descriptionController.text =
        context.read<RepairProvider>().problemDescription;
    phoneController.text = context.read<RepairProvider>().phoneNumber;
  }

  @override
  Widget build(BuildContext context) {
    final repairProvider = Provider.of<RepairProvider>(context);

    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: const Color.fromARGB(255, 241, 238, 238),
        appBar: AppBar(
          title: const Text('填写报修详情'),
          backgroundColor: const Color(0xFFF1F2F6),
          centerTitle: true,
          leading: IconButton(
              onPressed: () => Navigator.pop(context),
              icon: const Icon(Icons.arrow_back_ios)),
        ),
        body: Container(
            color: const Color(0xFFF1F2F6),
            child:
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              const Padding(
                padding: EdgeInsets.all(12),
                child: Text('报修房屋', style: TextStyle(color: Colors.black45)),
              ),
              InkWell(
                onTap: () {
                  TDPicker.showMultiPicker(context, title: '选择房屋',
                      onConfirm: (selected) {
                    repairProvider.setSelectedHouse(rooms[selected[0]].name);
                    Navigator.of(context).pop();
                  }, data: [rooms.map((room) => room.name).toList()]);
                },
                child: Container(
                  padding: const EdgeInsets.all(12),
                  width: double.infinity,
                  color: Colors.white,
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(repairProvider.selectedHouse,
                            style: const TextStyle(
                                fontSize: 14, color: Colors.black87)),
                        const Icon(Icons.arrow_forward_ios,
                            color: Colors.black45, size: 14)
                      ]),
                ),
              ),
              const Padding(
                padding: EdgeInsets.all(12),
                child: Text('报修信息', style: TextStyle(color: Colors.black45)),
              ),
              //报修项目
              Container(
                padding: const EdgeInsets.all(12),
                color: Colors.white,
                child: InkWell(
                    onTap: () {
                      TDPicker.showMultiPicker(context, title: '选择地区',
                          onConfirm: (selected) {
                        repairProvider
                            .setSelectedRepair(repairItems[selected[0]].name);
                        Navigator.of(context).pop();
                      }, data: [repairItems.map((item) => item.name).toList()]);
                    },
                    child: Row(children: [
                      const Expanded(
                          flex: 3,
                          child: Text('维修项目',
                              style: TextStyle(color: Colors.black87))),
                      Expanded(
                          flex: 7,
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(repairProvider.selectedRepair,
                                    style: const TextStyle(
                                        fontSize: 14, color: Colors.black87)),
                                const Icon(
                                  Icons.arrow_forward_ios,
                                  color: Colors.black45,
                                  size: 14,
                                )
                              ])),
                    ])),
              ),
              //手机号码
              Container(
                  padding: const EdgeInsets.all(12),
                  color: Colors.white,
                  child: Row(children: [
                    const Expanded(
                        flex: 3,
                        child: Text('联系电话',
                            style: TextStyle(color: Colors.black87))),
                    Expanded(
                      flex: 7,
                      child: TextField(
                          controller: phoneController,
                          maxLength: 11,
                          style: const TextStyle(fontSize: 14),
                          onChanged: (value) {
                            repairProvider.setPhoneNumber(value);
                          },
                          decoration: const InputDecoration(
                              isCollapsed: true,
                              counterText: '',
                              border: InputBorder.none,
                              hintText: '请输入联系电话号码')),
                    )
                  ])),
              //报修时间
              Container(
                padding: const EdgeInsets.all(12),
                color: Colors.white,
                child: InkWell(
                    onTap: () {
                      TDPicker.showDatePicker(context, title: '选择时间',
                          onConfirm: (selected) {
                        String date =
                            '${selected['year'].toString().padLeft(4, '0')}-${selected['month'].toString().padLeft(2, '0')}-${selected['day'].toString().padLeft(2, '0')}';
                        repairProvider.setSelectedDate(date);
                        Navigator.of(context).pop();
                      },
                          dateStart: [2024, 11, 20],
                          dateEnd: [2025, 12, 31],
                          initialDate: [2024, 11, 20]);
                    },
                    child: Row(children: [
                      const Expanded(
                          flex: 3,
                          child: Text('预约日期',
                              style: TextStyle(color: Colors.black87))),
                      Expanded(
                          flex: 7,
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(repairProvider.selectedDate,
                                    style: const TextStyle(
                                        fontSize: 14, color: Colors.black87)),
                                const Icon(
                                  Icons.arrow_forward_ios,
                                  color: Colors.black45,
                                  size: 14,
                                )
                              ])),
                    ])),
              ),
              //问题描述
              Container(
                  padding: const EdgeInsets.all(12),
                  color: Colors.white,
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Text('问题描述',
                            style: TextStyle(color: Colors.black87)),
                        TextField(
                            controller: descriptionController,
                            maxLines: null,
                            minLines: 4,
                            style: const TextStyle(fontSize: 14),
                            onChanged: (value) {
                              repairProvider.setProblemDescription(value);
                            },
                            textInputAction: TextInputAction.done,
                            decoration: const InputDecoration(
                                border: InputBorder.none,
                                isDense: true,
                                contentPadding: EdgeInsets.zero,
                                hintStyle: TextStyle(
                                    fontSize: 14, color: Colors.black45),
                                hintText: '请填写详细报修内容，有助于工作人员快速帮您解决问题。')),
                      ])),
              // 问题附件(上传图片)
              Container(
                  padding: const EdgeInsets.all(12),
                  width: double.infinity,
                  color: Colors.white,
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text('问题附件',
                            style: TextStyle(color: Colors.black87)),
                        GridView.builder(
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 4, // 每行显示4个图片
                            crossAxisSpacing: 8.0, // 水平间距
                            mainAxisSpacing: 8.0, // 垂直间距
                          ),
                          shrinkWrap: true, // 让GridView适应内容高度
                          physics: const NeverScrollableScrollPhysics(), // 禁止滚动
                          itemCount: repairProvider.imageUrlList.length < 8
                              ? repairProvider.imageUrlList.length + 1
                              : 8, // 如果图片少于8张，显示上传按钮
                          itemBuilder: (context, index) {
                            if (index < repairProvider.imageUrlList.length) {
                              final item = repairProvider.imageUrlList[index];
                              return Stack(
                                children: [
                                  ClipRRect(
                                    borderRadius:
                                        BorderRadius.circular(8.0), // 小圆角
                                    child: Image.network(item.url,
                                        width: 80,
                                        height: 80,
                                        fit: BoxFit.cover),
                                  ),
                                  Positioned(
                                    right: 4,
                                    top: 4,
                                    child: Container(
                                      alignment: Alignment.center,
                                      width: 16,
                                      height: 16,
                                      decoration: BoxDecoration(
                                        color: Colors.black38,
                                        borderRadius: BorderRadius.circular(50),
                                      ),
                                      child: GestureDetector(
                                        onTap: () {
                                          showGeneralDialog(
                                            context: context,
                                            pageBuilder:
                                                (BuildContext buildContext,
                                                    Animation<double> animation,
                                                    Animation<double>
                                                        secondaryAnimation) {
                                              return TDAlertDialog(
                                                title: '删除图片',
                                                rightBtnAction: () {
                                                  repairProvider
                                                      .removeImageUrlList(item);
                                                  Navigator.pop(context);
                                                },
                                              );
                                            },
                                          );
                                        },
                                        child: const Icon(
                                          Icons.close,
                                          color: Colors.white,
                                          size: 12, // 稍微调小一点size
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              );
                            } else {
                              return GestureDetector(
                                onTap: () {
                                  // 这里添加上传图片的逻辑
                                  addImage();
                                },
                                child: Container(
                                  width: 80,
                                  height: 80,
                                  decoration: BoxDecoration(
                                    color: Colors.grey[300],
                                    borderRadius: BorderRadius.circular(8.0),
                                  ),
                                  child: const Icon(Icons.add,
                                      size: 40, color: Colors.black),
                                ),
                              );
                            }
                          },
                        ),
                      ])),
              Container(
                  padding: const EdgeInsets.all(10),
                  color: Colors.white,
                  child: Row(children: [
                    Expanded(
                        child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.white,
                                foregroundColor: Colors.blue),
                            onPressed: () => submitRepair(),
                            child: const Column(children: [
                              SizedBox(height: 5),
                              Icon(Icons.add),
                              Text('提交报修'),
                              SizedBox(height: 5),
                            ])))
                  ]))
            ])));
  }

  @override
  void dispose() {
    context.read<RepairProvider>().clear();
    super.dispose();
  }
}
